package home.diy;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import android.os.AsyncTask;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class SshUpdate extends AsyncTask<Void, Void, String> {

	private String a = null;
	public Ecouteur ecouteur;

	@Override
	protected String doInBackground(Void... arg0) {
		String serverUrl = "192.168.0.14";
		String userName = "romanoff";
		String password = "stargate";

		JSch jsch = new JSch();
		Properties config = new Properties();
		config.put("StrictHostKeyChecking", "no");
		config.put("compression.s2c", "zlib,none");
		config.put("compression.c2s", "zlib,none");

		Session session;
		try {

			session = jsch.getSession(userName, serverUrl);
			session.setConfig(config);
			session.setPort(22);
			session.setPassword(password);
			session.connect();

			Channel channel = session.openChannel("exec");
			((ChannelExec) channel).setCommand("uname -a");
			channel.setInputStream(null);
			((ChannelExec) channel).setErrStream(System.err);

			InputStream in = channel.getInputStream();
			channel.connect();
			byte[] tmp = new byte[1024];
			while (true) {
				while (in.available() > 0) {
					int i = in.read(tmp, 0, 1024);
					if (i < 0)
						break;
					a += new String(tmp, 0, i);
				}
				if (channel.isClosed()) {
					System.out.println("exit-status: "
							+ channel.getExitStatus());
					break;
				}
				try {
					Thread.sleep(1000);
				} catch (Exception ee) {
				}
			}

			channel.disconnect();
			session.disconnect();
		} catch (JSchException e) {
			e.printStackTrace();
			return e.getMessage();
		} catch (IOException e) {
			e.printStackTrace();
			return e.getMessage();
		}
		return a;
	}

	protected void onPostExecute(String result) {
		a = result;
		// ecouteur.publishedResult(result);
	}

	public void addobserver(ServeurActivity a) {
		ecouteur = a;
	}

}
